// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

window.SOCKER_IO = null;

cc.Class({
    extends: cc.Component,

    properties: {

    },

    initServerModule(url) {
        console.log('initServerModule,url:' + url)
        // require('socket.io')
        SOCKER_IO = io(url)
    },

    sendJoinRoomEvent(roomId, userInfo){
        SOCKER_IO.emit('joinRoom', roomId, userInfo)
    },

    sendOnTouchMoveEvent(drawInfo) {
        SOCKER_IO.emit('onTouchMove', this.convertDrawInfoToSend(drawInfo))
    },


    sendClearDrawEvent() {
        SOCKER_IO.emit('clearDraw')
    },

    sendMsgEvent(msg) {
        SOCKER_IO.emit('sendMsg', msg)
    },

    registerOnTouchMove(brush) {
        let that = this
        SOCKER_IO.on('onTouchMove', (drawInfo) => {
            console.log("收到绘画广播:", drawInfo)
            drawInfo = that.convertDrawInfoFromReceived(drawInfo)
            brush.getComponent('Brush').doDraw(drawInfo.x0, drawInfo.y0, drawInfo.x1, drawInfo.y1, drawInfo.color, drawInfo.lineWidth)
        })
    },

    registerOnClearDraw(brush) {
        SOCKER_IO.on('clearDraw', () => {
            console.log("收到清除广播:")
            brush.getComponent('Brush').clearDraw()
        })
    },

    registerOnSendMsg(chatManager) {
        SOCKER_IO.on('sendMsg', (msg) => {
            console.log("收到消息广播:" + msg)
            chatManager.addOneMsg(msg)
        })

        SOCKER_IO.on('joinRoom', (msg) => {
            console.log("收到加入房间消息广播:" + msg)
            chatManager.addOneMsg(msg)
        })
    },

    convertDrawInfoToSend(info) {
        let drawInfo = {
            "lineWidth": info.lineWidth,
            "color": info.color,
            "x0": info.x0 / cc.winSize.width,
            "y0": info.y0 / cc.winSize.height,
            "x1": info.x1 / cc.winSize.width,
            "y1": info.y1 / cc.winSize.height,
        }
        return drawInfo
    },

    convertDrawInfoFromReceived(info) {
        let drawInfo = {
            "lineWidth": info.lineWidth,
            "color": info.color,
            "x0": info.x0 * cc.winSize.width,
            "y0": info.y0 * cc.winSize.height,
            "x1": info.x1 * cc.winSize.width,
            "y1": info.y1 * cc.winSize.height,
        }
        return drawInfo
    },
})
